<template>
    <div class="forum-container">
        <div v-for="post in posts" :key="post.id" class="post-item" @click="handlePostClick(post.id)">
            <h3>{{ post.title }}</h3>
            <p v-if="post.remark">{{ post.remark }}</p>
            <p v-else><em>暂无内容</em></p>
            <div class="post-meta">
                <span style="display: flex; align-items: center;"><el-icon style="margin-right: 3px;">
                        <User />
                    </el-icon>作者：{{ post.user.nickname }}</span> |
                <span style="display: flex; align-items: center;"><el-icon style="margin-right: 3px;">
                        <View />
                    </el-icon>浏览数：{{ post.visitCount }}</span> |
                <span style="display: flex; align-items: center;"><el-icon style="margin-right: 3px;">
                        <Star />
                    </el-icon>点赞数：{{ post.likeCount }}</span> |
                <span style="display: flex; align-items: center;"><el-icon style="margin-right: 3px;">
                        <Timer />
                    </el-icon>发布时间：{{ post.createTime }}</span> |
                <span style="display: flex; align-items: center;">更多<el-icon style="margin-left: 3px;">
                        <More />
                    </el-icon></span>

            </div>
        </div>

        <!-- 加载触发元素 -->
        <div ref="loader" class="loader">
            <!-- 使用Element Plus加载组件 -->
            <el-skeleton v-if="isLoading" :rows="5" animated />
            <!-- <el-skeleton v-if="isLoading && ifFirstLoad" :rows="3" animated style="margin-top: 20px;" />
            <el-skeleton v-if="isLoading && ifFirstLoad" :rows="5" animated style="margin-top: 20px;" />
            <el-skeleton v-if="isLoading && ifFirstLoad" :rows="2" animated style="margin-top: 20px;" /> -->

            <!-- 加载完成提示 -->
            <div v-if="noMoreData" class="no-more">
                <el-divider>
                    <el-icon>
                        <Finished />
                    </el-icon>
                    <span>已经到底啦</span>
                </el-divider>
            </div>

            <!-- 错误提示 -->
            <!-- <div v-if="isError" class="error-container">
                <el-alert title="加载失败" type="error" :closable="false" show-icon>
                    <template #default>
                        <el-button type="primary" size="small" @click="retry">重新加载</el-button>
                    </template>
                </el-alert>
            </div> -->
        </div>
    </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue';
import {
    ElSkeleton,
    ElDivider,
    ElIcon,
    ElAlert,
    ElButton
} from 'element-plus';
import { Finished } from '@element-plus/icons-vue';
import { getArticles } from '../api/articlesApi.js';
import router from '@/router/router.js'
import { useSearchStore } from '@/stores/searchStore';
import { watch } from 'vue';
import {searchArticles,boardArticles} from '../api/articlesApi.js';
import { useBoardStore } from '@/stores/boardStore';

export default {
    components: {
        ElSkeleton,
        ElDivider,
        ElIcon,
        ElAlert,
        ElButton,
        Finished
    },

    setup() {
        const searchStore = useSearchStore();
        const posts = ref([]);
        const page = ref(1);
        const isLoading = ref(false);
        const isError = ref(false);
        const noMoreData = ref(false);
        const loader = ref(null);
        const observer = ref(null);
        const ifFirstLoad = ref(true);
        const boardStore = useBoardStore();
        const flag = ref(false);


        const fetchPosts = async () => {
            console.log(flag.value);
            
            if (isLoading.value || noMoreData.value || flag.value) return;

            isLoading.value = true;
            isError.value = false;

            try {
                // 替换为实际API调用
                // const response = await fetchPostsFromAPI(page.value);
                // 改为调用 getArticles 接口
                const response = await getArticles({ currentPage: page.value, pageSize: 10 }); // 根据接口定义传参
                console.log(response);

                if (response.data.length === 0) {
                    noMoreData.value = true;
                    return;
                }

                posts.value = [...posts.value, ...response.data];
                page.value++;


                // 第一次加载完成后设置为 false
                if (ifFirstLoad.value) {
                    ifFirstLoad.value = false;
                }
            } catch (error) {
                isError.value = true;
                console.error('加载失败:', error);
            } finally {
                isLoading.value = false;
            }
        };

        const handlePostClick = (id) => {
            // 在新标签页中打开文章详情页
            const url = `/article/${id}`;
            window.open(url, '_blank');
            console.log('点击了帖子:', id);
        };


        const retry = () => {
            isError.value = false;
            fetchPosts();
        };

        const initObserver = () => {
            observer.value = new IntersectionObserver(
                (entries) => {
                    if (entries[0].isIntersecting) {
                        fetchPosts();
                    }
                },
                { threshold: 0.1 }
            );

            if (loader.value) {
                observer.value.observe(loader.value);
            }
        };

        onMounted(() => {
            fetchPosts();
            initObserver();
        });

        onUnmounted(() => {
            if (observer.value) {
                observer.value.disconnect();
            }
        });

        watch(
  () => searchStore.searchKeyword,
  async (newKeyword) => {
    if (newKeyword) {
      console.log('搜索关键词已更新:', newKeyword);
      // 可以在此处调用搜索 API 或过滤帖子列表
    //   performSearch(newKeyword);
        const resp = await searchArticles(newKeyword);
        searchStore.setSearchKeyword("")
        // console.log(resp);
        posts.value = resp
        flag.value = true;
    }
  }
);

watch(
  () => boardStore.activeBoardId,
  async (newVal) => {
    console.log('板块切换为:', newVal);

    // 如果是“全部板块”，则加载默认文章列表
    if (newVal == 0) {
      posts.value = [];           // 清空当前列表
      page.value = 1;             // 重置分页
      noMoreData.value = false;   // 恢复加载状态
      flag.value = false;         // 允许触发无限滚动

      initObserver();             // 重新绑定观察器（如果之前被移除过）

      await fetchPosts();         // 加载第一页数据
    } else {
      // 如果是其他板块，则只显示该板块的数据
      const resp = await boardArticles(newVal);
      posts.value = resp;
      flag.value = true;          // 禁止触发无限滚动
    }
  }
);

        return {
            posts,
            isLoading,
            isError,
            noMoreData,
            loader,
            retry,
            handlePostClick
        };
    }
};
</script>

<style scoped>
/* .post-meta {
    font-size: 12px;
    color: #666;
    margin-top: 10px;
} */
.post-meta {
    display: flex;
    flex-wrap: wrap;
    /* 可选：自动换行 */
    align-items: center;
    font-size: 12px;
    color: #666;
    margin-top: 10px;
    gap: 10px;
    /* 设置项目之间的间距 */
}

.forum-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 0;
}

.post-item {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.post-item:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
}

.loader {
    margin-top: 20px;
    padding: 20px;
}

.no-more {
    text-align: center;
    color: #909399;
    font-size: 14px;
}

.no-more .el-icon {
    margin-right: 8px;
    vertical-align: middle;
}

.error-container {
    margin: 20px 0;
}
</style>